# 1.古诗文登录的案例
#     <1>用超级鹰(或者自己输入)模拟登录古诗文网站(https://www.gushiwen.cn/)

import re

import requests

from chaojiying import Chaojiying_Client

session = requests.session()  #session方法用于一个页面获取多个数据


def get_viewstae():
    # 1. 登录__VIEWSTATE值
    url = "https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx"
    r = session.get(url).text
    viewstae = re.search('id="__VIEWSTATE" value="(.*?)"', r).group(1)
    # print(viewstae)
    return viewstae


def get_verify():
    # 2.拿到验证码
    url = "https://so.gushiwen.cn/RandCode.ashx?t=1679205920516"
    img_code = session.get(url).content
    with open('img.gif', 'wb') as f:
        f.write(img_code)

    chaojiying = Chaojiying_Client('cjy2998', 'gxd2998', '946058')  # 用户中心>>软件ID 生成一个替换 96001
    im = open('img.gif', 'rb').read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
    # print(chaojiying.PostPic(im, 1902))  # 1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()
    verify = chaojiying.PostPic(im, 1902)['pic_str']
    print(verify)
    # print chaojiying.PostPic(base64_str, 1902)  #此处为传入 base64代码
    return verify


def login(viewstae, verify):
    # 3. 登录
    url = "https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx"
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.41'
    }

    data = {
        '__VIEWSTATE': viewstae,#不能写死
'__VIEWSTATEGENERATOR': 'C93BE1AE',
'from': 'http://so.gushiwen.cn/user/collect.aspx',
'email': '16633402998',
'pwd': 'gxd2998',
'code': verify,#不能写死
'denglu': '登录'
    }

    # 来登录
    r = session.post(url, headers=headers, data=data).text
    print(r)
    with open('古诗文网.html', 'w', encoding='utf-8-sig') as f:
        f.write(r)




if __name__ == '__main__':
    # 1.登录__VIEWSTATE值
    viewstae = get_viewstae()
    # 2.拿到验证码
    verify = get_verify()
    # 3. 登录
    login(viewstae, verify)

